package service

import (
	"errors"
	"fmt"
	"github.com/dgrijalva/jwt-go"
	"gopkg.in/yaml.v2"
	"io/ioutil"
	"os"
	"oss-api/boot"
	"oss-api/library/request"
	"oss-api/library/response"
	"time"
)

var Config = new(ConfigService)

type ConfigService struct{}

// CheckConfig 检查配置是否存在
func (c *ConfigService) CheckConfig() (bool, error) {
	_, err := os.Stat("config/config.yaml")
	if err != nil {
		if os.IsExist(err) {
			return false, nil
		}
		return false, err
	}
	return true, nil
}

func readConfig(config boot.OssConfig) error {
	bytes, err := yaml.Marshal(&config)
	if err != nil {
		return err
	}
	return ioutil.WriteFile("config/config.yaml", bytes, 0777)
}

// DatabaseConfig 配置MySQL
func (c *ConfigService) DatabaseConfig(data request.InstallDatabaseVo) (bool, error) {
	var db boot.DataBaseConfig
	// root:123456@tcp(192.168.31.138:3306)/oss-cloud?charset=utf8mb4&parseTime=True&loc=Local
	db.Base.Link = fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&parseTime=True&loc=Local", data.Username, data.Password, data.Ip, data.Part, data.Database)
	db.Base.AutoPing = true
	db.Base.Singular = false
	db.Base.Prefix = data.TablePrefix
	db.Base.MaxIdleConns = 10
	db.Base.MaxOpenConns = 100
	db.Logger.Color = true
	db.Logger.Level = "debug"
	db.Logger.Path = "/tmp"
	db.Logger.Slow = 1
	boot.Config.Database = db
	// 重载配置
	boot.DB = boot.InitDB()

	return true, nil
}

// StorageConfig 数据源配置
func (c *ConfigService) StorageConfig(data request.InstallStorageVo) (bool, error) {
	// TODO 暂时只支持阿里对象存储，后期扩展
	boot.Config.Storage = boot.StorageConfig{
		Default: data.DefaultSource,
		Cloud: boot.StorageCloud{
			Endpoint:        data.Endpoint,
			AccessKeyId:     data.AccessKeyId,
			AccessKeySecret: data.AccessKeySecret,
			UseCname:        data.UseCname,
		},
	}
	return true, nil
}

// UserConfig 用户信息配置
func (c *ConfigService) UserConfig(data request.InstallUsernameVo) (bool, error) {
	boot.Config.User = boot.UserConfig{
		Username: data.Username,
		Password: data.Password,
		Email:    data.Email,
	}
	// 写入配置信息到文件
	if err := readConfig(boot.Config); err != nil {
		return false, err
	}
	return true, nil
}

// UserLogin 用户登陆
func (c *ConfigService) UserLogin(data request.InstallLoginVo) (response.LoginUserVo, error) {
	user := boot.Config.User
	if user.Username != data.Username || user.Password != data.Password {
		return response.LoginUserVo{}, errors.New("账号后者密码错误")
	}
	claims := OssClaims{
		username: user.Username,
		password: user.Password,
		StandardClaims: jwt.StandardClaims{
			NotBefore: time.Now().Unix(),
			ExpiresAt: time.Now().Unix() + 3600*24,
			Issuer:    "oss-cloud",
		},
	}

	token, err := jwt.NewWithClaims(jwt.SigningMethodHS256, claims).SignedString([]byte("oss-cloud"))
	if err != nil {
		return response.LoginUserVo{}, errors.New("登陆失败")
	}
	return response.LoginUserVo{
		Username: data.Username,
		Password: data.Password,
		Email:    user.Email,
		Token:    token,
	}, nil
}
